/*
 * @Author: liusuyun
 * @Date: 2021-12-05 15:57:39
 * @LastEditors: liusuyun
 * @LastEditTime: 2021-12-05 20:50:38
 * @Description:获取时间区间的方法
 */
import dayjs from 'dayjs';
export const getNumberDays = (
  number = 1,
  date = new Date(),
  format = 'YYYY-MM-DD HH:mm:ss'
) => {
  let timestamp = '';
  let newDate = '';
  if (!(date instanceof Date)) {
    date = new Date(date.replace(/-/g, '/'));
  }
  timestamp = date.getTime();
  newDate = new Date(timestamp + number * 24 * 3600 * 1000);
  return dayjs(newDate).format(format);
};

// 获取一天的开始时间
const startTime = (time, format) => {
  time = time || new Date();
  return dayjs(new Date(time).setHours(0, 0, 0, 0)).format(format);
};

// 获取一天的结束时间
const endTime = (time, format) => {
  time = time || new Date();
  return dayjs(new Date(time).setHours(23, 59, 59, 999)).format(format);
};

// 获取某天当前周的开始时间和结束时间
export const getWeekStartAndEndTime = (
  time = new Date(),
  format = 'YYYY-MM-DD HH:mm:ss',
  isMonfirstDay = 1
) => {
  let current = '';
  if (!(time instanceof Date)) {
    current = new Date(time);
  } else {
    current = time;
  }

  // current是本周的第几天
  let nowDayOfWeek = current.getDay();
  if (isMonfirstDay) {
    if (nowDayOfWeek === 0) nowDayOfWeek = 7;
  }
  const dayNum = 1 * 24 * 60 * 60 * 1000;
  // 获取本周星期一的时间，星期一作为一周的第一天
  const firstDate = new Date(current.valueOf() - (nowDayOfWeek - 1) * dayNum);
  // 获取本周星期天的时间，星期天作为一周的最后一天
  const lastDate = new Date(new Date(firstDate).valueOf() + 6 * dayNum);
  return {
    startTime: startTime(firstDate, format),
    endTime: endTime(lastDate, format)
  };
};

// 获取某月的开始时间和结束时间  不传默认为当前月
export const getMonthStartAndEndTime = (
  time = new Date(),
  format = 'YYYY-MM-DD HH:mm:ss'
) => {
  let date = '';
  if (!(time instanceof Date)) {
    date = new Date(time);
  } else {
    date = time;
  }
  //   const date = time ? new Date(time) : new Date();
  const startDate = date.setDate(1);
  const currentMonth = date.getMonth();
  const nextMonth = currentMonth + 1;
  const nextMonthFirstDay = new Date(date.getFullYear(), nextMonth, 1);
  const oneDay = 24 * 60 * 60 * 1000;
  const endDate = nextMonthFirstDay - oneDay;
  return {
    startTime: startTime(startDate, format),
    endTime: endTime(endDate, format)
  };
};